package org.mili.ticketeer.ui.role;

import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.ContactRole;
import org.mili.ticketeer.dto.Role;
import org.mili.ticketeer.service.RoleService;
import org.mili.ticketeer.service.ServiceException;
import org.mili.ticketeer.service.ServiceFactory;
import org.mili.ticketeer.ui.ManyToManyTableModel;

import java.util.List;

/**
 */
public class ContactRoleTableModel extends ManyToManyTableModel<Contact, ContactRole> {
    private RoleService roleService = ServiceFactory.getService(RoleService.class);
    private Contact contact;

    public ContactRoleTableModel() {
        super(new String[]{"No.", "Included?", "Name"});
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        ContactRole contactRole = get(rowIndex);
        switch(columnIndex) {
            case 0:
                return rowIndex + 1;
            case 1:
                return contactRole.getContact() > 0;
            case 2:
                try {
                    return roleService.findRoleById(contactRole.getRole()).getName();
                } catch (ServiceException e) {
                    e.printStackTrace();
                }

            default: throw new IllegalStateException("no column index for: " + columnIndex);
        }
    }

    public void setValueAt(Object value, int row, int col) {
        try {
            Boolean set = (Boolean) value;
            ContactRole contactRole = get(row);
            Role role = roleService.findRoleById(contactRole.getRole());
            if (set) {
                roleService.assign(contact, role);
            } else {
                roleService.unassign(contact, role);
            }
            update(contact);
            fireModelChange(contact, contactRole);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ContactRole> load(Contact contact) {
        this.contact = contact;
        try {
            if (contact == null) {
                return roleService.getContactRoles();
            } else {
                return roleService.getContactRolesFor(contact);
            }
        } catch (ServiceException e) {
            throw new IllegalStateException(e);
        }
    }

}
